package org.vectrics.user.web.struts;

import javax.servlet.jsp.JspException;

import org.vectrics.provider.CoreServiceLocator;
import org.vectrics.struts.VectricsActionData;
import org.vectrics.struts.VectricsStrutsAction;
import org.vectrics.user.Person;

public class SavePasswordAction extends VectricsStrutsAction {

	@Override
	protected String doExecute(VectricsActionData actionData) throws JspException {
		
        // Si presiono cancelar va a cancel
        if (actionData.wasButtonPressed("cancel")) {
        	return "success";
        }
		UserPasswordForm form = (UserPasswordForm)actionData.getForm();
		String newPassword = form.getPassword();
		String personIdParam = form.getPersonId();

		Person person = getPersonWithPasswordToSave(actionData);
		person.getUser().setPassword(newPassword);
		person.getUser().setPasswordEncrypted(false);
		CoreServiceLocator.getPersonService().updateUser(person.getUser());
		
		return "success";
	}
	
	protected Person getPersonWithPasswordToSave(VectricsActionData actionData) {
		UserPasswordForm form = (UserPasswordForm)actionData.getForm();
		String personIdParam = form.getPersonId();
		return CoreServiceLocator.getPersonService().findPersonById(new Long(personIdParam));
	}
	
}
